package com.igirl.common.service;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.igirl.common.bean.HttpClientResult;

/**
 * httpclient调用接口的工具类
 * @author Henry
 *
 */
@Service
public class ApiService {

	
	 //应用将httpclient对象的创建交给spring托管,也就是去spring的IOC容器中注册httpclient对象
	 @Autowired(required=false)
	 private CloseableHttpClient httpclient;
	 
	/**
	 * 无参的doGet请求
	 * @param url
	 * @return 响应状态码默认为200 
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String doGet(String url) throws ClientProtocolException, IOException{
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        //调用接口后响应对象 : 响应状态  响应内容
        CloseableHttpResponse response = null;
        String content = getResult(httpGet, response);
        return content;
	}
	
	/**
	 * 无参的Post请求
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public HttpClientResult doPost(String url) throws ClientProtocolException, IOException{

        // 创建http POST请求    输入URL
        HttpPost httpPost = new HttpPost(url);
        //模拟了浏览器来进行访问  
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        CloseableHttpResponse response = null;
        return getPostResult(httpPost, response);
    }

    private HttpClientResult getPostResult(HttpPost httpPost, CloseableHttpResponse response) throws IOException {
        try {
            // 执行请求    敲回车
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200 返回响应状态码  还要返回响应结果
            int code = response.getStatusLine().getStatusCode();
            String data = EntityUtils.toString(response.getEntity(), "UTF-8");
            return new HttpClientResult(code, data);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    /**
	 * 有参的Get请求
	 * @param url
	 * @param params Map<参数名称,参数值>
	 * @return
	 * @throws URISyntaxException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String doGetParam(String url,Map<String,String> params) throws URISyntaxException, ClientProtocolException, IOException{
        // 定义请求的参数
        URIBuilder uriBuilder = new URIBuilder(url);
        //参数传递方式
        for(String key : params.keySet()){
        	 uriBuilder.setParameter(key, params.get(key));
        }
        //build方法创建出URI对象
        URI uri = uriBuilder.build();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);
        CloseableHttpResponse response = null;
        String content = getResult(httpGet, response);
        if (content != null) {
            return content;
        }
        return null;
	}

    private String getResult(HttpGet httpGet, CloseableHttpResponse response) throws IOException {
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                return content;
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }


    /**
	 * 有参的Post请求
	 * @param url Map<参数名，参数值>
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public HttpClientResult doPostParam(String url,Map<String,String> params) throws ClientProtocolException, IOException{

        // 创建http POST请求    输入URL
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        for(String key : params.keySet()){
        	 parameters.add(new BasicNameValuePair(key, params.get(key)));
        }
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
        // 将请求实体设置到httpPost对象中    设置post请求提交的表单
        httpPost.setEntity(formEntity);
        
        //模拟了浏览器来进行访问  
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        CloseableHttpResponse response = null;
        return getPostResult(httpPost, response);
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
